from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Request, Header
from sqlalchemy.orm import Session
from app.common.enums.resp_enum import ErrTypes
from app.common.exceptions import GenericException

from app.utils.resp_util import APIResponse
from app.dependencies.db import get_db
from app import utils, services, conf

import logging
logger = logging.getLogger(__name__)

router = APIRouter(prefix='/callback', tags=['callback'])
#router = APIRouter(dependencies=[Depends(get_query_token2)],)


@router.post("/callback_demo/{merc_no}", response_model=APIResponse)
async def callback_demo(merc_no, request: Request, x_xpay_signature: Annotated[str, Header()], db: Session = Depends(get_db)):
    logger.info('----------------- [通知回调] callback_demo2 -----------------')
    #print('params: %s' % param.model_dump())
    resp = APIResponse()
    cb_dto = await request.json()
    print('回调数据: %s' % cb_dto)
    #signature = cb_dto.get('signature')
    signature = x_xpay_signature
    encrypted_data = cb_dto.get('encrypted_data')
    
    # 验签, 解密
    merc_key_obj = services.merc.get_merc_key(db, merc_no)
    if merc_key_obj.status != 1:
        raise GenericException(ErrTypes.merc_key_invalid)
    secret_key = merc_key_obj.secret_key
    pay_util = utils.pay.BzPayUtil(secret_key=secret_key, 
                                        pri_key=conf.SM_PRI_KEY, 
                                        pub_key=conf.SM_PUB_KEY)
    #pay_util = bz_pay_util.BzPayUtil(secret_key=key)
    
    data = pay_util.decrypt_with_sm4(encrypted_data)
    logger.info(f'data: {data}')
    if data:
        res = pay_util.verify_with_sm2(data, signature)
        if res:
            logger.info('验签通过')
        else:
            logger.error('验签失败')
    resp.message = '已收到回调.'
    resp.data = data
    
    return resp

@router.post("/callback_demo", response_model=APIResponse)
async def callback_demo(request: Request, db: Session = Depends(get_db)):
    logger.info('----------------- [通知回调] callback_demo -----------------')
    #print('params: %s' % param.model_dump())
    resp = APIResponse()
    data = await request.json()
    print('data: %s' % data)
    resp.message = 'callback received.'
    resp.data = data
    return resp

